﻿Public Class TaskForm
    Dim s As State = New State(state.TASK_STATE_IN_PLANNING_ID)
    Dim task As Task = New Task(s)

    Public Sub New()
        InitializeComponent()
    End Sub

    Public Sub New(ByRef taskParam As Task)
        InitializeComponent()
        task = taskParam
    End Sub

    Private Sub TaskForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        GenericAdministrator.loadComboBox(Me.cboProject, ProjectAdministrator.search(), "id", "name")
        GenericAdministrator.loadComboBox(Me.cboTaskType, GenericAdministrator.searchDataByFilter(New TaskType), "id", "name")
        Me.cboProject.SelectedIndex = -1
        Me.cboTaskType.SelectedIndex = -1

        Util.cleanComboBox(Me.cboProjectActivities)
        Me.cboProjectActivities.Enabled = False

        Util.cleanComboBox(Me.cboProjectMembers)
        Me.cboProjectMembers.Enabled = False

        Dim state As State = StateAdministrator.searchDataById(state.TASK_STATE_IN_PLANNING_ID)
        Me.txtState.Text = state.nameProperty

        Me.txtTaskName.Focus()

        'Controla rangos de fechas
        configurarRangoFechas(dtpEstimatedFromDate, dtpEstimatedToDate)

        If task.idProperty > 0 Then
            loadFormToEdit()
        End If
        task.getTaskState.initForm(Me, task)
    End Sub

    Private Sub loadFormToEdit()
        Me.txtTaskName.Text = task.nameProperty
        Me.cboProject.SelectedValue = task.projectActivityProperty.projectProperty.idProperty
        Me.cboProject.Enabled = False
        Me.cboProjectActivities.SelectedValue = task.projectActivityProperty.idProperty
        Me.cboProjectActivities.Enabled = False
        Me.cboTaskType.SelectedValue = task.taskTypeProperty.idProperty
        Me.cboProjectMembers.SelectedValue = task.projectMemberProperty.idProperty
        Me.rtxtObservations.Text = task.observationsProperty
        Me.dtpEstimatedFromDate.Text = task.estimatedStartDateProperty
        Me.dtpEstimatedToDate.Text = task.estimatedEndDateProperty
        Me.txtState.Text = task.stateProperty.nameProperty


        For Each progressTask As TaskProgress In task.progressTaskProperty
            Dim progressTaskDate As String = progressTask.taskProgressDateProperty
            Dim startHour As String = progressTask.startHourProperty
            Dim endHour As String = progressTask.endHourProperty
            Dim percentage As String = progressTask.percentageProperty
            Dim taskProgressObservations As String = progressTask.observationsProperty
            Me.dgvProgressTask.Rows.Add(progressTaskDate, startHour, endHour, percentage, taskProgressObservations)
        Next
    End Sub

    Private Sub cmdAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdAdd.Click
        If validateAddProgressTask() Then
            Dim progressTaskDate As String = Me.dtpDate.Text
            Dim startHour As String = Me.txtStartHour.Text
            Dim endHour As String = Me.txtEndHour.Text
            Dim percentage As String = Me.txtProgressTask.Text
            Dim observations As String = Me.rtxtProgressTaskObservations.Text
            Me.dgvProgressTask.Rows.Add(progressTaskDate, startHour, endHour, percentage, observations)
            cleanProgressTaskTab()
        End If
    End Sub

    Private Sub cleanProgressTaskTab()
        Me.txtStartHour.Text = ""
        Me.txtEndHour.Text = ""
        Me.txtProgressTask.Text = ""
        Me.rtxtProgressTaskObservations.Text = ""
    End Sub

    Private Sub cmdRemove_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdRemove.Click
        Dim confirmacion As Integer
        If Me.dgvProgressTask.Rows.Count > 0 Then
            confirmacion = MsgBox("¿Está seguro que desea Eliminar el Avance seleccionado?", vbYesNo + vbQuestion + vbDefaultButton2, "Salir")
            If confirmacion = vbYes Then
                Me.dgvProgressTask.Rows.Remove(Me.dgvProgressTask.CurrentRow)
            End If
        End If
    End Sub

    Private Sub cmdCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdCancel.Click
        Dim Result As DialogResult

        Result = MessageBox.Show(Me, "Esta seguro que desea salir?", "Atencion", MessageBoxButtons.YesNo, _
            MessageBoxIcon.Question, MessageBoxDefaultButton.Button2)
        If Result = System.Windows.Forms.DialogResult.Yes Then
            Me.Close()
        End If
    End Sub

    Private Function validateRequiredFields() As Boolean
        If cboProject.SelectedIndex = -1 Then
            MsgBox("Debe seleccionar un Proyecto", MsgBoxStyle.Critical, vbYes)
            cboProject.Focus()
            Return False
        End If

        If txtTaskName.Text = "" Then
            MsgBox("Debe ingresar un Nombre", MsgBoxStyle.Critical, vbYes)
            txtTaskName.Focus()
            Return False
        End If

        If cboProjectActivities.SelectedIndex = -1 Then
            MsgBox("Debe seleccionar una Tarea", MsgBoxStyle.Critical, vbYes)
            cboProject.Focus()
            Return False
        End If

        If cboTaskType.SelectedIndex = -1 Then
            MsgBox("Debe seleccionar un Tipo de Tarea", MsgBoxStyle.Critical, vbYes)
            cboProject.Focus()
            Return False
        End If

        If cboProjectMembers.SelectedIndex = -1 Then
            MsgBox("Debe seleccionar un Recurso", MsgBoxStyle.Critical, vbYes)
            cboProject.Focus()
            Return False
        End If

        Return True
    End Function

    Private Function validateAddProgressTask() As Boolean
        If Me.txtStartHour.Text = "" Then
            MsgBox("Debe ingresar una Hora de Inicio", MsgBoxStyle.Critical, vbYes)
            txtStartHour.Focus()
            Return False
        End If

        If Me.txtEndHour.Text = "" Then
            MsgBox("Debe ingresar una Hora de Fin", MsgBoxStyle.Critical, vbYes)
            txtEndHour.Focus()
            Return False
        End If

        If Me.txtProgressTask.Text = "" Then
            MsgBox("Debe ingresar un Porcentaje de Avance", MsgBoxStyle.Critical, vbYes)
            txtProgressTask.Focus()
            Return False
        End If

        If Me.rtxtProgressTaskObservations.Text = "" Then
            MsgBox("Debe ingresar una Observación", MsgBoxStyle.Critical, vbYes)
            rtxtProgressTaskObservations.Focus()
            Return False
        End If

        If (CDbl(Me.txtProgressTask.Text) < 0.1 Or CDbl(Me.txtProgressTask.Text) > 100) Then
            MsgBox("El Porcentaje de Avance debe ser mayor a 0% y menor a 100%", MsgBoxStyle.Critical, vbYes)
            txtProgressTask.Focus()
            Return False
        End If

        If (Me.dgvProgressTask.Rows.Count > 0) Then
            Dim maxPercentageOfTask As Integer = Me.dgvProgressTask.Rows(Me.dgvProgressTask.Rows.Count - 1).Cells(3).Value
            If (CDbl(Me.txtProgressTask.Text) <= maxPercentageOfTask) Then
                MsgBox("El Porcentaje del nuevo avance debe ser mayor al del avance anterior", MsgBoxStyle.Critical, vbYes)
                txtProgressTask.Focus()
                Return False
            End If
        End If

        If (CInt(Me.txtStartHour.Text) < 0 Or CInt(Me.txtStartHour.Text) > 23) Then
            MsgBox("La hora de inicio debe ser entre las 0 hs y las 23 hs", MsgBoxStyle.Critical, vbYes)
            txtProgressTask.Focus()
            Return False
        End If

        If (CInt(Me.txtEndHour.Text) < 0 Or CInt(Me.txtEndHour.Text) > 23) Then
            MsgBox("La hora de fin debe ser entre las 0 hs y las 23 hs", MsgBoxStyle.Critical, vbYes)
            txtProgressTask.Focus()
            Return False
        End If

        Return True
    End Function

    Private Sub cmdSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSave.Click
        Dim row As DataGridViewRow
        Dim progressTaskList As New ArrayList

        If validateRequiredFields() = True Then
            For Each row In dgvProgressTask.Rows
                Dim progressTaskDate As Date = CDate(row.Cells("progressTaskDate").Value)
                Dim startHour As String = row.Cells("startHour").Value
                Dim endHour As String = row.Cells("endHour").Value
                Dim percentage As Double = row.Cells("percentage").Value
                Dim taskProgressObservations As String = row.Cells("observations").Value

                Dim progressTask As TaskProgress = New TaskProgress(Nothing, progressTaskDate, startHour, endHour, percentage, taskProgressObservations)
                progressTaskList.Add(progressTask)
            Next

            Dim projectActivityId As Integer = cboProjectActivities.SelectedValue
            Dim projectActivity As New ProjectActivity(projectActivityId)
            Dim name As String = Me.txtTaskName.Text
            Dim taskTypeId As Integer = cboTaskType.SelectedValue
            Dim taskType As New TaskType(taskTypeId)
            Dim projectMemberId As Integer = cboProjectMembers.SelectedValue
            Dim projectMember As New ProjectMember(projectMemberId)
            Dim observations As String = Me.rtxtObservations.Text
            Dim estimatedFromDate As Date = CDate(Me.dtpEstimatedFromDate.Value.ToString("dd/MM/yyyy"))
            Dim estimatedToDate As Date = CDate(Me.dtpEstimatedToDate.Value.ToString("dd/MM/yyyy"))

            task.projectActivityProperty = projectActivity
            task.nameProperty = name
            task.taskTypeProperty = taskType
            task.projectMemberProperty = projectMember
            task.observationsProperty = observations
            task.estimatedStartDateProperty = estimatedFromDate
            task.estimatedEndDateProperty = estimatedToDate
            task.progressTaskProperty = progressTaskList

            TaskAdministrator.save(task)

            Me.Close()
            searchTasksForm.Show()
        End If
    End Sub

    Private Sub cboProject_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboProject.SelectedIndexChanged
        Try
            Dim projectId As Integer = Me.cboProject.SelectedValue
            Dim project As New Project(projectId)
            Dim projectActivity As ProjectActivity = New ProjectActivity(project)
            Dim projectMember As ProjectMember = New ProjectMember(project)

            Util.cleanComboBox(Me.cboProjectActivities)
            Me.cboProjectActivities.Enabled = True
            GenericAdministrator.loadComboBox(Me.cboProjectActivities, ProjectActivityAdministrator.searchDataByFilter(projectActivity), "pa_id", "a_name")

            Util.cleanComboBox(Me.cboProjectMembers)
            Me.cboProjectMembers.Enabled = True
            GenericAdministrator.loadComboBox(Me.cboProjectMembers, ProjectMemberAdministrator.searchDataByFilter(projectMember), "PM_ID", "name")
        Catch
            ' No hace nada
        End Try
    End Sub

    Private Sub dtpEstimatedFromDate_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dtpEstimatedFromDate.ValueChanged
        configurarRangoFechas(dtpEstimatedFromDate, dtpEstimatedToDate)
    End Sub

    Private Sub dtpEstimatedToDate_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dtpEstimatedToDate.ValueChanged
        configurarRangoFechas(dtpEstimatedFromDate, dtpEstimatedToDate)
    End Sub

    Private Sub cmdStartTask_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdStartTask.Click
        task.getTaskState().comenzar(task)
        Dim Result As DialogResult

        Result = MessageBox.Show(Me, "Esta seguro que desea comenzar la tarea? Se guardaran los cambios", "Atencion", MessageBoxButtons.YesNo, _
            MessageBoxIcon.Question, MessageBoxDefaultButton.Button2)
        If Result = System.Windows.Forms.DialogResult.Yes Then
            Me.cmdSave_Click(Nothing, Nothing)
        End If
    End Sub

    Private Sub txtProgressTask_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtProgressTask.KeyPress
        ViewValidators.isFloat(e)
    End Sub

    Private Sub txtStartHour_KeyPress(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtStartHour.KeyPress
        ViewValidators.isInteger(e)
    End Sub

    Private Sub txtEndHour_KeyPress(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtEndHour.KeyPress
        ViewValidators.isInteger(e)
    End Sub
End Class